package leetcode;

/**
 * 判断两个二叉树是否相等
 *
 * @author 王霄
 * @date 2022/2/7 16:56
 **/
public class Tree {

    /**
     * 定义节点
     */
    public static class Node {
        int val;
        Node left, right;

        Node(int x) {
            val = x;
        }
    }

    public static void main(String[] args) {
        Node node1 = new Node(2);
        node1.left = new Node(1);
        node1.right = new Node(4);

        Node node2 = new Node(3);
        node2.left = new Node(1);
        node2.right = new Node(4);

        System.out.println(isSameTree(node1, node2));
    }

    public static boolean isSameTree(Node node1, Node node2) {
        //若两棵树均为空
        if (node1 == null && node2 == null) {
            return true;
        }
        //若两棵树有一方为空
        else if (node1 == null || node2 == null) {
            return false;
        }
        //两棵树都不为空
        else {
            //如果节点数据不相同
            if (node1.val != node2.val) {
                return false;
            }
            //如果节点数据相同
            else {
                //递归判断左右节点是否也相同
                return isSameTree(node1.left, node2.left) && isSameTree(node1.right, node2.right);
            }
        }
    }
}
